package com.boot.stomp.interceptor;

import com.boot.stomp.authentication.StompAuthenticationHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.security.Principal;
import java.util.Arrays;

@Slf4j
public class MultipleChannelInterceptor implements ChannelInterceptor {

    private final StompAuthenticationHandler[] authenticationHandlers;

    public MultipleChannelInterceptor(StompAuthenticationHandler[] authenticationHandlers) {
        log.debug(Arrays.toString(authenticationHandlers));
        this.authenticationHandlers = authenticationHandlers;
    }

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        //1. 判断是否首次连接请求
        assert accessor != null;
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            //2. 验证是否登录
            for (StompAuthenticationHandler authenticationHandler : authenticationHandlers) {
                Principal principal = authenticationHandler.getPrincipal(accessor);
                if (principal != null) {
                    log.debug("用户 {} 试图登录", principal.getName());
                    if (authenticationHandler.authentication(principal)) {
                        log.debug("验证成功，用户 {} 登录成功", principal.getName());
                        accessor.setUser(principal);
                        return message;
                    }
                    log.error("验证失败，用户 {} 登录失败", principal.getName());
                }
            }
            log.error("未知用户试图登录");
            return null;
        }
        //不是首次连接，已经成功登陆
        return message;
    }

}
